package com.example.himg_rong.bofangqiapp;

import android.content.Intent;
import android.graphics.Color;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class MainActivity extends AppCompatActivity {
    private TextView tvLocal;
    private TextView tvOnline;
    private ListView lvMusic;
    private ImageView ivRefresh;
    private List<Music> localMusicList = new LinkedList<Music>();
    private List<Music> onlineMusicList = new LinkedList<Music>();
    private BaseAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //绑定Bmob
        Bmob.initialize(MainActivity.this,"037ad39ec5d26c884f63ef4be86e9a72");
        //初始化组件（绑定ID）
        initView();
        //加载本地文件夹文件
        initLocalData();
        //显示ListView
        showItem(localMusicList);

        tvLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvLocal.setTextColor(Color.parseColor("#ffffff"));
                tvOnline.setTextColor(Color.parseColor("#80ffffff"));
                showItem(localMusicList);
                lvMusic.setVisibility(View.VISIBLE);
                ivRefresh.setVisibility(View.GONE);
            }
        });

        tvOnline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvOnline.setTextColor(Color.parseColor("#ffffff"));
                tvLocal.setTextColor(Color.parseColor("#80ffffff"));
                //刷新网络音乐
                refreshOnlineData();
                //显示ListView
                showItem(onlineMusicList);
            }
        });

        lvMusic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<Music> musicList = new LinkedList<Music>();
                for(int i=0;i<adapter.getCount();i++){
                    Music music = (Music)adapter.getItem(i);
                    musicList.add(music);
                }
//                Toast.makeText(MainActivity.this,music.getName(),Toast.LENGTH_SHORT).show();
                showPlayer(musicList,position);
            }
        });
    }

    private void showPlayer(List<Music> musicList,int curr) {
        Intent intent = new Intent(MainActivity.this,PlayerActivity.class);
        intent.putExtra("MusicList", (Serializable) musicList);
        intent.putExtra("Curr",curr);
        startActivity(intent);
    }

    //判断是否为MP3格式且添加到musicList(音乐列表)
    private void isMp3(String musicName,String musicUrl,List<Music> musicList){
        int index = musicName.indexOf(".");
        if(musicName.substring(index).equals(".mp3")){
            Music music = new Music(musicName,musicUrl);
            musicList.add(music);
        }
    }

    private void initView() {
        tvLocal = findViewById(R.id.tv_local);
        tvOnline = findViewById(R.id.tv_online);
        lvMusic = findViewById(R.id.lv_music);
        ivRefresh = findViewById(R.id.iv_refresh);
    }

    private void initLocalData() {
        File path = new File("/mnt/shared/Other");
        File[] files = path.listFiles();
        if (files == null){
            Log.e("error","空目录");
        }else{
            for(File file : files) {
//                String str = file.getName();
////                Log.e("files.length:", str.substring(str.lastIndexOf(".")));
//                int index = str.indexOf(".");
//                if(str.substring(index).equals(".mp3")){
//                    Music music = new Music(str.substring(0,index),file.getPath());
//                    localMusicList.add(music);
//                }
                isMp3(file.getName(),file.getPath(),localMusicList);
            }
        }
    }

    private void showItem(final List<Music> musicList) {
        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return musicList.size();
            }

            @Override
            public Object getItem(int position) {
                return musicList.get(position);
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                LayoutInflater inflater = MainActivity.this.getLayoutInflater();
                View view;

                if (convertView==null) {
                    view = inflater.inflate(R.layout.item, null);
                }else{
                    view=convertView;
                }
//                ImageView ivMusic = view.findViewById(R.id.iv_music);
                TextView tvMusic = view.findViewById(R.id.tv_music);
                tvMusic.setText(musicList.get(position).getName());
                return view;
            }
        };
        lvMusic.setAdapter(adapter);
    }

    public void refreshOnlineData() {
        lvMusic.setVisibility(View.GONE);
        ivRefresh.setVisibility(View.VISIBLE);

        BmobQuery<MusicFile> musicFileBmobQuery = new BmobQuery<MusicFile>();
        musicFileBmobQuery.findObjects(new FindListener<MusicFile>() {
            @Override
            public void done(List<MusicFile> list, BmobException e) {
                if (list.size()>0){
                    onlineMusicList.clear();
                    for (MusicFile musicFile : list){
//                        String str = musicFile.getMusic().getFilename();
//                        int index = str.indexOf(".");
//                        if(str.substring(index).equals(".mp3")){
//                            Music music = new Music(str.substring(0,index),musicFile.getMusic().getFileUrl());
//                            onlineMusicList.add(music);
//                        }
                        isMp3(musicFile.getMusic().getFilename(),musicFile.getMusic().getFileUrl(),onlineMusicList);
                    }

                    lvMusic.setVisibility(View.VISIBLE);
                    ivRefresh.setVisibility(View.GONE);

                    adapter.notifyDataSetChanged();
                }else {
                    Toast.makeText(MainActivity.this,"暂无歌曲",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
